package com.xiaoyi.utils;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.io.LineIterator;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Iterator;

public class FileUtilsCompat {
    public static final String ROOT_PATH = System.getProperty("user.dir");

    /**
     * 存放文件内容
     *
     * @param fileName
     * @return
     */
    public static void wirteStr2File(String str, String fileName) {
        File file = new File(fileName);
        if (!file.exists()) {
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        try {
            org.apache.commons.io.FileUtils.writeStringToFile(file, str, "UTF-8");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 存放文件内容
     *
     * @param fileName
     * @return
     */
    public static void wirteStr2File(String str, String fileName, boolean append) {
        File file = new File(fileName);
        if (!file.exists()) {
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        try {
            org.apache.commons.io.FileUtils.writeStringToFile(file, str, "UTF-8", append);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取文件内容
     *
     * @param fileName
     * @return
     */
    public static String getStrFromFile(String fileName) {
        File file = new File(fileName);
        if (!file.exists()) {
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        String res = "";
        try {
            FileInputStream inputStream = new FileInputStream(file);
            res = IOUtils.toString(inputStream, "UTF-8");
        } catch (IOException e) {
            res = "";
        }
        return res;
    }

    //读取文件
    public static LineIterator getFileLine(String filepath) throws IOException {
            return FileUtils.lineIterator(new File(filepath), "UTF-8");
    }
}
